import {
  Form,
  Typography,
  Input,
  Radio,
  InputNumber,
  Space,
  Button,
  Card,
  Spin,
  message,
  Switch,
  Empty,
  TableColumnType,
  InputRef,
  Tag,
  Tooltip,
  Divider,
} from "antd";
import {
  PageContainer,
  ProDescriptions,
  ProTable,
} from "@ant-design/pro-components";
import { useEffect, useRef, useState } from "react";
import { namespace } from "../configFile";
import { connect, useParams, history } from "umi";
import styles from "../styles.less";
import { CardType, EffectiveType } from "@/constants";
import Https from "@/utils/Https";
import { ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import { FilterDropdownProps } from "antd/es/table/interface";
import { getItem } from "@/utils/localstorage";
import { VipCategoryEnum, vipTypeList } from "@/utils/common";
//import { getColumnSearchProps } from "@/utils/common/filter";
const { Text } = Typography;

const PayPanel = (props) => {
  const { dispatch, prev, info, isFooter } = props;
  const [payForm] = Form.useForm();
  const payAppoint = Form.useWatch("payAppoint", payForm);
  const vipcardAppoint = Form.useWatch("vipcardAppoint", payForm);
  const [dataSource, setDataSource] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [loading, setLoading] = useState(false);
  const [onlinePaymentFlag, setonlinePaymentFlag] = useState(0);
  const params = useParams();
  const [searchText, setSearchText] = useState("");
  const [searchedColumn, setSearchedColumn] = useState("");
  const searchInput = useRef<InputRef>(null);

  const handleSearch = (
    selectedKeys: string[],
    confirm: FilterDropdownProps["confirm"],
    dataIndex: any
  ) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters: () => void) => {
    clearFilters();
    setSearchText("");
  };

  const getColumnSearchProps = (dataIndex: any): TableColumnType<any> => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
      close,
    }) => (
      <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
        <Input
          ref={searchInput}
          placeholder={`请输入会员卡名称`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() =>
            handleSearch(selectedKeys as string[], confirm, dataIndex)
          }
          style={{ marginBottom: 8, display: "block" }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() =>
              handleSearch(selectedKeys as string[], confirm, dataIndex)
            }
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            检索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              close();
            }}
          >
            关闭
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered: boolean) => (
      <SearchOutlined style={{ color: filtered ? "#1677ff" : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes((value as string).toLowerCase()),
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
    render: (text) => text,
  });
  useEffect(() => {
    if (props.vipCardList.length) {
      if (Object.keys(info).length > 0) {
        let objList = [];
        let selectKeys = [];
        let selectRowList = [];
        const useableVenueCourseList = info.useableVenueCourseList || [];
        props.vipCardList.map((item, index) => {
          const hasData = useableVenueCourseList.find((card) => {
            return card.vipcardId === item.id;
          });
          if (hasData) {
            selectKeys.push(hasData.vipcardId);
            selectRowList.push({
              key: item.id,
              vipcardId: item.id,
              vipcardName: item.vipcardName,
              vipType: item.vipType,
              vipCategory: item.vipCategory,
              deductNum: hasData
                ? item.vipType == 1
                  ? (Number(hasData.deductNum) / 100).toFixed(2)
                  : Number(hasData.deductNum)
                : 0,
            });
          }
          objList.push({
            key: item.id,
            vipcardId: item.id,
            vipcardName: item.vipcardName,
            vipType: item.vipType,
            vipCategory: item.vipCategory,
            isUniversal: item.isUniversal,
            cardLimit: item.cardLimit,
            effectiveValue: item.effectiveValue,
            effectiveType: item.effectiveType,
            deductNum: hasData
              ? item.vipType == 1
                ? (Number(hasData.deductNum) / 100).toFixed(2)
                : Number(hasData.deductNum)
              : 0,
          });
        });
        setDataSource(objList);
        setSelectedRowKeys(selectKeys);
        setSelectedRows(selectRowList);
      } else {
        let objList = [];
        props.vipCardList.map((item) => {
          objList.push({
            key: item.id,
            vipcardId: item.id,
            vipcardName: item.vipcardName,
            vipType: item.vipType,
            vipCategory: item.vipCategory,
            deductNum: 1,
            isUniversal: item.isUniversal,
            cardLimit: item.cardLimit,
            effectiveValue: item.effectiveValue,
            effectiveType: item.effectiveType,
          });
        });
        setDataSource(objList);
      }
    }
  }, [props.vipCardList]);
  //设置初始值
  const setFormValue = (info) => {
    const {
      onlinePaymentFlag,
      payAppoint,
      vipcardAppoint,
      payOriginalPrice,
      payCouponPrice,
    } = info;
    payForm.setFieldsValue({
      onlinePaymentFlag: Number(onlinePaymentFlag),
      payAppoint: Number(payAppoint),
      vipcardAppoint: Number(vipcardAppoint),
      payOriginalPrice: payOriginalPrice
        ? (Number(payOriginalPrice) / 100).toFixed(2)
        : 0,
      payCouponPrice: payCouponPrice
        ? (Number(payCouponPrice) / 100).toFixed(2)
        : 0,
    });
    setonlinePaymentFlag(info.onlinePaymentFlag);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      setSelectedRowKeys(selectedRowKeys);
      setSelectedRows(selectedRows);
    },
    getCheckboxProps: (record) => ({
      // 根据数据项的属性动态设置选择框属性
      disabled: record.isUniversal == "1",
    }),
  };

  const deductNumChange = (e, record, index) => {
    let newDataSource = [...dataSource];
    newDataSource[index].deductNum = e;
    setDataSource(newDataSource);
    selectedRows.map((item) => {
      if (item.vipcardId === record.vipcardId) {
        item.deductNum = record.deductNum;
      }
    });
  };

  const submit = () => {
    let newSelectRows = JSON.parse(JSON.stringify(selectedRows));
    newSelectRows.map((item) => {
      if (item.vipType == 1) {
        item.deductNum = item.deductNum * 100;
      }
    });
    payForm.validateFields().then(async (request) => {
      request.useableVenueCourseList =
        request.onlinePaymentFlag == "1" ? newSelectRows : [];
      request.payCouponPrice = request.payCouponPrice
        ? Number(request.payCouponPrice) * 100
        : 0;
      request.payOriginalPrice = request.payOriginalPrice
        ? Number(request.payOriginalPrice) * 100
        : 0;
      request.payAppoint = payAppoint == 1 ? 1 : 0;
      request.vipcardAppoint = 1;
      if (params.num) {
        let obj = {
          id: params.id,
          ...request,
          venueId: info.venueId,
        };
        let res: any = await Https.post("/course/updateInfo", obj, true);
        setLoading(true);
        if (res.code === 200) {
          message.success("保存成功");
          history.push("/course/info", { courseType: params.courseType });
        } else {
          message.error(res.msg);
        }
        setLoading(false);
      } else {
        props.submit(2, request);
      }
    });
  };
  useEffect(() => {
    if (Object.keys(info).length > 0) {
      setFormValue(info);
      dispatch({
        type: `${namespace}/getVipCardList`,
        params: {
          current: 1,
          pageSize: 1000,
        },
      });
    } else {
      dispatch({
        type: `${namespace}/getVipCardList`,
        params: {
          current: 1,
          pageSize: 1000,
        },
      });
    }
  }, [info]);
  return (
    <Spin spinning={loading}>
      <PageContainer
        footer={[
          isFooter ? (
            <div className={styles.formBtn}>
              {params.num ? (
                <Button
                  loading={loading}
                  type="primary"
                  size="large"
                  onClick={() => submit()}
                >
                  保存
                </Button>
              ) : (
                <>
                  <Button size="large" onClick={() => prev()}>
                    上一步
                  </Button>
                  <Button
                    type="primary"
                    size="large"
                    style={{ marginLeft: "20px" }}
                    onClick={() => submit()}
                    loading={loading}
                  >
                    提交
                  </Button>
                </>
              )}
            </div>
          ) : null,
        ]}
      >
        <Form
          form={payForm}
          className={styles.payForm}
          initialValues={{
            onlinePaymentFlag: 0,
            payAppoint: 0,
            vipcardAppoint: 1,
          }}
        >
          <Card
            title="开卡支付设置"
            style={{ marginBottom: "16px" }}
            extra={
              <Form.Item
                label="是否支持线上支付"
                name="onlinePaymentFlag"
                style={{ marginBottom: "0px" }}
              >
                <Switch
                  checkedChildren="开启"
                  unCheckedChildren="关闭"
                  onChange={(e) => {
                    let val = e ? 1 : 0;
                    payForm.resetFields();
                    payForm.setFieldsValue({ onlinePaymentFlag: val });
                    setonlinePaymentFlag(val);
                  }}
                />
              </Form.Item>
            }
          >
            {onlinePaymentFlag == 1 ? (
              <>
                <ProDescriptions title="付费预约设置">
                  <Form.Item label="付费预约" name="payAppoint">
                    <Radio.Group
                      onChange={(e) => {
                        const { value } = e.target;
                        if (value == 0) {
                          payForm.setFieldsValue({
                            payOriginalPrice: 0,
                            payCouponPrice: 0,
                          });
                        } else {
                          payForm.setFieldsValue({
                            payOriginalPrice: 0.01,
                            payCouponPrice: 0.01,
                          });
                        }
                      }}
                    >
                      <Radio value={1}>开启</Radio>
                      <Radio value={0}>关闭</Radio>
                    </Radio.Group>
                  </Form.Item>
                  {payAppoint === 1 ? (
                    <>
                      <Form.Item
                        label="原价(元/节)"
                        name="payOriginalPrice"
                        rules={[{ required: true, message: "请输入原价" }]}
                      >
                        <InputNumber
                          style={{ width: "100%" }}
                          controls={false}
                          min={0.01}
                          precision={2}
                          suffix="元/节"
                          addonBefore="¥"
                          placeholder="请输入原价"
                        />
                      </Form.Item>
                      <Form.Item
                        label="销售价(元/节)"
                        tooltip={"课程实际售价"}
                        name="payCouponPrice"
                        rules={[{ required: true, message: "请输入销售价" }]}
                      >
                        <InputNumber
                          style={{ width: "100%" }}
                          placeholder="请输入优惠价"
                          controls={false}
                          min={0.01}
                          suffix="元/节"
                          addonBefore="¥"
                          precision={2}
                        />
                      </Form.Item>
                    </>
                  ) : null}
                </ProDescriptions>
                <ProDescriptions
                  title={
                    <span>
                      会员卡预约设置
                      <ReloadOutlined
                        style={{ color: "#1677FF", marginLeft: "5px" }}
                        title="刷新会员卡列表"
                        onClick={() => {
                          setLoading(true);
                          dispatch({
                            type: `${namespace}/getVipCardList`,
                            params: {
                              current: 1,
                              pageSize: 1000,
                            },
                            callback: (res) => {
                              setLoading(false);
                            },
                          });
                        }}
                      />
                    </span>
                  }
                ></ProDescriptions>
                <ProTable
                  pagination={false}
                  search={false}
                  options={false}
                  rowSelection={rowSelection}
                  tableAlertOptionRender={() => {
                    return null;
                  }}
                  rowKey="key"
                  columns={[
                    {
                      title: "类型",
                      dataIndex: "vipType",
                      // width:100,
                      filters: [
                        { text: "储值卡", value: "1" },
                        { text: "期限卡", value: "2" },
                        { text: "次数卡", value: "3" },
                      ],
                      onFilter: (value, record) =>
                        record.vipType.includes(value as string),
                      render: (text, record) => {
                        return <span>{CardType[record.vipType].text}</span>;
                      },
                    },
                    {
                      title:"卡信息",
                      tooltip:"通：通用卡关联的课程，品牌方统一管理，如果编辑请在“品牌管理/连锁管理/通用卡 中进行编辑通用卡”",
                      width:200,
                      dataIndex: "vipcardName",
                      ...getColumnSearchProps("vipcardName"),
                      filterIcon: (filtered) => (
                        <SearchOutlined
                          style={{ color: filtered ? "#1890ff" : undefined }}
                        />
                      ),
                      render: (_, record) => {
                        return (
                          <Space size="small">
                            <Tag color="processing">
                              {record.isUniversal == "1" ? "通｜" : ""}
                              {VipCategoryEnum[record.vipCategory].shortName}
                            </Tag>
                            <Text>{record.vipcardName}</Text>
                            </Space>
                        );
                      },
                    },
                    {
                      title: "卡额度",
                      dataIndex: "cardLimit",
                      width:"150",
                      render: (text, record) => {
                        return record.cardLimit ? (
                          <span>
                            {record.vipType == 1
                              ? (Number(record.cardLimit) / 100).toFixed(2) +
                                vipTypeList[record.vipType].status
                              : record.vipType == 3
                                ? Number(record.cardLimit) +
                                  vipTypeList[record.vipType].status
                                : "-"}
                          </span>
                        ) : (
                          "-"
                        );
                      },
                    },
                    {
                      title: "有效期",
                      dataIndex: "effectiveValue",
                      hideInSearch: true,
                      width:"150",
                      render: (_, record) => {
                        return record.effectiveType ? (
                          <span>
                            {record.effectiveValue}
                            {EffectiveType[record.effectiveType].text}
                          </span>
                        ) : (
                          "-"
                        );
                      },
                    },
                    {
                      title: "收费价格",
                      dataIndex: "deductNum ",
                      width: 250,
                      responsive: ['xl'],
                      fixed: "right",
                      render: (text, record, index) => {
                        return record.vipType != 2 ? (
                          record.isUniversal == "1" ? (
                            selectedRowKeys.includes(record.key) ? (
                              <span>
                                单节课收费:
                                {record.deductNum}
                                {CardType[record.vipType].unit}/人
                              </span>
                            ) : (
                              "-"
                            )
                          ) : (
                            <div
                              style={{
                                display: "flex",
                                justifyContent: "flex-start",
                                alignItems: "center",
                              }}
                            >
                              <span style={{ width: "100px", flexShrink: 0 }}>
                                单节课收费:
                              </span>
                              <InputNumber
                                value={record.deductNum}
                                min={1}
                                controls={false}
                                precision={record.vipType == 1 ? 2 : 0}
                                addonAfter={
                                  CardType[record.vipType].unit + "/人"
                                }
                                //style={{ width: "80%" }}
                                onChange={(e) => {
                                  console.log(e);
                                  if (!e) {
                                    e = 1;
                                  }
                                  deductNumChange(e, record, index);
                                }}
                              />
                              {/* <span>{CardType[record.vipType].unit}/人</span> */}
                            </div>
                          )
                        ) : (
                          "-"
                        );
                      },
                    },
                  ]}
                  scroll={{ x:800, y: 500 }}
                  dataSource={dataSource}
                />
              </>
            ) : (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={<div>不支持线上支付</div>}
              />
            )}
          </Card>
        </Form>
      </PageContainer>
    </Spin>
  );
};

export default connect((state) => {
  return {
    ...state[namespace],
    submitLoading: state.loading.effects[`${namespace}/submitItem`],
  };
})(PayPanel);
